package org.apache.shardingsphere.elasticjob.lite.ui.util;

import org.apache.shardingsphere.elasticjob.lite.ui.domain.EventTraceDataSourceConfiguration;
import org.apache.shardingsphere.elasticjob.lite.ui.domain.RegistryCenterConfiguration;
import org.apache.shardingsphere.elasticjob.lite.ui.security.UserAccount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description session utils class
 * @Author JL
 */
@Component
public class SessionUtils {

    public static final String REG_CENTER_CONFIG_KEY = "reg_center_config_key";
    public static final String DATA_SOURCE_CONFIG_KEY = "data_source_config_key";
    private static final String SESSION_LOGIN_USER = "session_login_user";
    private static final String SIGN_CHAR = "_";

    @Autowired
    public HttpServletRequest request;

    public HttpServletRequest getRequest(){
        return request;
    }

    public UserAccount getSessionUser(){
        HttpSession session = getHttpSession();
        return (UserAccount) session.getAttribute(SESSION_LOGIN_USER);
    }

    public HttpSession getHttpSession(){
        return request.getSession();
    }

    public RegistryCenterConfiguration getRegistryCenterConfiguration(){
        HttpSession session = getHttpSession();
        UserAccount user = getSessionUser();
        String sessionKey = REG_CENTER_CONFIG_KEY.concat(SIGN_CHAR).concat(user.getUsername());
        return (RegistryCenterConfiguration) session.getAttribute(sessionKey);
    }

    public EventTraceDataSourceConfiguration getEventTraceDataSourceConfiguration(){
        HttpSession session = getHttpSession();
        UserAccount user = getSessionUser();
        String sessionKey = DATA_SOURCE_CONFIG_KEY.concat(SIGN_CHAR).concat(user.getUsername());
        return (EventTraceDataSourceConfiguration) session.getAttribute(sessionKey);
    }

    public void cleanEventTraceDataSourceConfiguration(String username){
        HttpSession session = getHttpSession();
        String sessionKey = DATA_SOURCE_CONFIG_KEY.concat(SIGN_CHAR).concat(username);
        session.removeAttribute(sessionKey);
    }

    public void cleanRegistryCenterConfiguration(String username){
        HttpSession session = getHttpSession();
        String sessionKey = REG_CENTER_CONFIG_KEY.concat(SIGN_CHAR).concat(username);
        session.removeAttribute(sessionKey);
    }

}
